package com.yst.webplugin.additional.transform;



import com.yst.web.utils.EventBusUtils;
import com.yst.web.utils.ThreadUtil;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * utils for transform use dictionary
 */
public final class TransDictUtil {

    public interface IDictionaryCreator {
        Map<Object,DictionaryItem> create();
    }

    private static final Map<String, Map<Object,DictionaryItem>> dictList;
    private static final Map<String, IDictionaryCreator> creatorList;
    static {
        dictList= Collections.synchronizedMap(new HashMap<>());
        creatorList=Collections.synchronizedMap(new HashMap<>());
    }

    /**
     * fetch all dictionaries
     * @return all dictionaries
     */
    public static Map<String,Map<Object,DictionaryItem>> getDictionaries(){
        return Collections.unmodifiableMap(dictList);
    }

    /**
     * fetch specific dictionary
     * @param dictionaryName name of dictionary
     * @return Dictionary
     */
    public static Map<Object,DictionaryItem> getDictionary(String dictionaryName){
        return dictList.get(dictionaryName);
    }

    /**
     * append dictionary
     * @param dictionaryName name of dictionary
     * @param dictionary dictionary {@link Map}
     */
    public static void addDictionary(String dictionaryName,Map<Object,DictionaryItem> dictionary){
        dictList.put(dictionaryName,dictionary);
    }

    /**
     * remove specific dictionary
     * @param dictionaryName name of dictionary
     */
    public static void removeDictionary(String dictionaryName){
        dictList.remove(dictionaryName);
    }

    /**
     * Reload dictionary
     * @param dictionaryName dictionary name
     */
    public static void reloadDictionary(String dictionaryName){
        if (creatorList.containsKey(dictionaryName)){
            dictList.remove(dictionaryName);
            ThreadUtil.execute(()->{
                dictList.put(dictionaryName,creatorList.get(dictionaryName).create());
            });
        }
    }

    /**
     * register a dictionary creator
     * @param dictionaryName dictionary name
     * @param creator dictionary creator
     */
    public static void registerDictionaryCreator(String dictionaryName,IDictionaryCreator creator){
        creatorList.put(dictionaryName,creator);
    }

    /**
     * remove a dictionary creator
     * @param dictionaryName dictionary name
     */
    public static void removeDictionaryCreator(String dictionaryName){
        creatorList.remove(dictionaryName);
    }

}
